<?php
namespace app\service\http\yzt\social;

use app\model\user\UserModel;
use app\service\http\yzt\YztHttpClient;
use hunma\exception\ApiException;
use support\Db;
use support\Redis;

class Social extends YztHttpClient
{



    public function send()
    {

        //　增加排除上次发布的用户id
        $lastUserId = Redis::get('last_published_user_id')??999999; // 默认值为999999，避免查询不到数据

        /**
         * 随机获取动态信息
         * 请求发布接口
         */
        $dynamic = Db::table('user_dynamics')
            ->where('publish_status', 0)  // 未发布
            ->where('review_status', 1)   // 审核通过
            ->where('user_id','!=', $lastUserId)   // 用户不等于
            ->whereNull('delete_time')    // 未删除
            ->inRandomOrder()
            ->first();

        if(!(isset($dynamic->id) && $dynamic->id)){
            throw new ApiException('没有可发布的动态');
        }

        // 查看用户信息
        $user = UserModel::getOne(['id' => $dynamic->user_id], ['account', 'password', 'id']);

        if(!$user){
            throw new ApiException('用户不存在');
        }

        $data = [
            'content'=>$dynamic->content,
            'area_id'=>1,
            'visibility'=>2,
            'account' => $user['account'],
        ];

        $res = $this->post('/api/social/post', $data);

        Redis::setEx('last_published_user_id', 86400, $dynamic->user_id); // 设置1小时过期时间，避免重复发布同一用户的动态

        // 成功后修改发布状态
        if ($res['code'] == 200){
            Db::table('user_dynamics')
                ->where('id', $dynamic->id)
                ->update(['publish_status' => 1]);
        } else {
            throw new ApiException($res['msg']);
        }

        return $res;
    }

}